// PrefTab.cpp : implementation file
//

#include "stdafx.h"
#include "moretunes.h"
#include "PrefTab.h"
#include ".\preftab.h"
#include "misc.h"

#define SERVER_US "www.amazon.com"
#define SERVER_UK "www.amazon.co.uk"
#define SERVER_DE "www.amazon.de"
#define SERVER_FR "www.amazon.fr"
#define FILE_PREFS "mtpf.dat"

// CPrefTab dialog

IMPLEMENT_DYNAMIC(CPrefTab, CResizablePage)
CPrefTab::CPrefTab()
	: CResizablePage(CPrefTab::IDD)
	, _registration(_T("~9"))
	, _autoScanData(0)
	, _autoSearchData(1)
	, _copyrightData(_T(""))
	, _editCoverData(_T(""))
	, _editP2PData(_T(""))
	, _encoderData(_T(""))
	, _fileNameData(_T(""))
	, _resultsData(0)
	, _serverData(0)
	, _name(_T(""))
	, _email(_T(""))
	, _key(_T(""))
	, _onlyV1Data(0)
	, _duplicateData(0)
	, _existingData(0)
	, _systrayData(0)
	, _heigthData(0)
	, _trackFormatData(0)
	, _windowTop(100)
	, _windowLeft(100)
	, _mini(0)
	, _miniTop(100)
	, _miniLeft(100)
	, _onStartupData(0)
	, _proxyData(0)
	, _proxyServerData(_T(""))
	, _numFormatData(0)
	, _coverArtData(0)
	, _WMPCompatibleData(0)
	, _firstTime(0)
{
	// Load the prefs
	CFile fp;

	// Sets the current directory to the app folder
	CString appName;
	appName = AfxGetAppName();
	appName += ".exe";
	CString appPath;
	char buf[512];
	GetModuleFileName(AfxGetInstanceHandle(), buf, 512);
	appPath = buf;
	appPath.Replace(appName, "");
	SetCurrentDirectory(appPath);

	if (fp.Open(FILE_PREFS, CFile::modeRead)) {
		try {
			CArchive ar (&fp, CArchive::load);
			if (ar.IsLoading())
				ar >> _autoScanData >> _autoSearchData >> _copyrightData >> _editCoverData >> _editP2PData;
				ar >> _encoderData >> _fileNameData >> _name >> _email >> _key >> _resultsData >> _serverData;
				ar >> _onlyV1Data >> _duplicateData >> _existingData >> _systrayData >> _heigthData;
				ar >> _trackFormatData >> _windowTop >> _windowLeft >> _mini >> _miniTop >> _miniLeft;
				ar >> _onStartupData >> _proxyData >> _proxyServerData >> _numFormatData >> _coverArtData;
				ar >> _WMPCompatibleData;
			ar.Close();
		}
		catch(CArchiveException* ex){
			setDefault();
			ex->Delete();
		}
		fp.Close();
	}
	else {
		_firstTime = TRUE;
		setDefault();
	}

	_registration = REGISTRATION_OK;
}

int CPrefTab::saveData(void) {
	CFile fp;
	LaunchOnStartup(_onStartupData);
	if (fp.Open(FILE_PREFS, CFile::modeCreate | CFile::modeWrite)) {
		try {
			CArchive ar (&fp, CArchive::store);
			if( ar.IsStoring() ) {
				ar << _autoScanData << _autoSearchData << _copyrightData << _editCoverData << _editP2PData;
				ar << _encoderData << _fileNameData << _name << _email << _key << _resultsData << _serverData;
				ar << _onlyV1Data << _duplicateData << _existingData << _systrayData << _heigthData;
				ar << _trackFormatData << _windowTop << _windowLeft << _mini << _miniTop << _miniLeft;
				ar << _onStartupData << _proxyData << _proxyServerData << _numFormatData << _coverArtData;
				ar << _WMPCompatibleData;
				ar.Close();
				return TRUE;
			}
			else
				return FALSE;
		}
		catch (CArchiveException *ex) {
			ex->Delete();
			return FALSE;
		}
		fp.Close();
	}
	return FALSE;
}

///////////////////////////////////////////////////////////////////////////////////////
// Modify under this for prefs you can see
///////////////////////////////////////////////////////////////////////////////////////

#define SAVED "Preferences saved\n\n\
Some preferences will be active after you restart moreTunes"
#define SAVED_FAILED "Saving failed!"

// Store the prefs
void CPrefTab::OnBnClickedSave() {
	_autoScanData = _autoScan.GetCheck();
	_autoSearchData = _autoSearch.GetCheck();
	_copyright.GetWindowText(_copyrightData);
	_editCover.GetWindowText(_editCoverData);
	_editP2P.GetWindowText(_editP2PData);
	_encoder.GetWindowText(_encoderData);
	_fileName.GetWindowText(_fileNameData);
	_resultsData = _results.GetCheck();
	_serverData = _server.GetCurSel();
	_onlyV1Data = _onlyV1.GetCheck();
	_duplicateData = _duplicate.GetCheck();
	_existingData = _existing.GetCheck();
	_systrayData = _systray.GetCheck();
	_trackFormatData = _trackFormat.GetCheck();
	_onStartupData = _onStartup.GetCheck();
	_proxyData = _proxy.GetCheck();
	_proxyServer.GetWindowText(_proxyServerData);
	_numFormatData = _numFormat.GetCheck();
	_coverArtData = _coverArt.GetCheck();
	_WMPCompatibleData = _WMPCompatible.GetCheck();

	if (saveData() == TRUE)
		AfxMessageBox(SAVED, MB_ICONINFORMATION);
	else 
		AfxMessageBox(SAVED_FAILED, MB_ICONINFORMATION);
	Invalidate();
	UpdateWindow();
}

#define AUTOSCAN_DEFAULT 0
#define AUTOSEARCH_DEFAULT 1
#define COPYRIGHT_DEFAULT "?"
#define COVER_DEFAULT "c:\\"
#define P2P_DEFAULT "c:\\Program Files\\Kazaa\\Kazaa.exe"
#define ENCODER_DEFAULT "?"
#define FILENAME_DEFAULT "ARTIST - TITLE"
#define RESULTS_DEFAULT 0
#define SERVER_DEFAULT 0
#define ONLYV1_DEFAULT 0
#define DUPLICATE_DEFAULT 1
#define EXISTING_DEFAULT 1
#define SYSTRAY_DEFAULT 0
#define TRACK_FORMAT_DEFAULT 0
#define ON_STARTUP_DEFAULT 0
#define PROXY_DEFAULT 0
#define NUM_FORMAT_DEFAULT 0
#define COVER_ART_DEFAULT 1
#define WMP_COMPATIBLE_DEFAULT 1

// prefs you can see
int CPrefTab::setDefault(void) {
	_autoScanData = AUTOSCAN_DEFAULT;
	_autoSearchData = AUTOSEARCH_DEFAULT;
	_copyrightData = COPYRIGHT_DEFAULT;
	_editCoverData = COVER_DEFAULT;
	_editP2PData = P2P_DEFAULT;
	_encoderData = ENCODER_DEFAULT;
	_fileNameData = FILENAME_DEFAULT;
	_resultsData = RESULTS_DEFAULT;
	_serverData = SERVER_DEFAULT;
	_onlyV1Data = ONLYV1_DEFAULT;
	_duplicateData = DUPLICATE_DEFAULT;
	_existingData = EXISTING_DEFAULT;
	_systrayData = SYSTRAY_DEFAULT;
	_trackFormatData = TRACK_FORMAT_DEFAULT;
	_onStartupData = ON_STARTUP_DEFAULT;
	_proxyData = PROXY_DEFAULT;
	_numFormatData = NUM_FORMAT_DEFAULT;
	_coverArtData = COVER_ART_DEFAULT;
	_WMPCompatibleData = WMP_COMPATIBLE_DEFAULT;
	return 0;
}

void CPrefTab::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	_autoScan.SetCheck(_autoScanData);
	_autoSearch.SetCheck(_autoSearchData);
	_copyright.SetWindowText(_copyrightData);
	_editCover.SetWindowText(_editCoverData);
	_editP2P.SetWindowText(_editP2PData);
	_encoder.SetWindowText(_encoderData);
	_fileName.SetWindowText(_fileNameData);
	_results.SetCheck(_resultsData);
	_server.SetCurSel(_serverData);
	_onlyV1.SetCheck(_onlyV1Data);
	_duplicate.SetCheck(_duplicateData);
	_existing.SetCheck(_existingData);
	_systray.SetCheck(_systrayData);
	_trackFormat.SetCheck(_trackFormatData);
	_onStartup.SetCheck(_onStartupData);
	_proxy.SetCheck(_proxyData);
	_proxyServer.SetWindowText(_proxyServerData);
	_numFormat.SetCheck(_numFormatData);
	_coverArt.SetCheck(_coverArtData);
	_WMPCompatible.SetCheck(_WMPCompatibleData);
}


/////////////////////////////////////////////////////////////////////////
// Don't have to touch the code below to add a pref
/////////////////////////////////////////////////////////////////////////

void CPrefTab::OnBnClickedBrowseCover()
{
	LPMALLOC pMalloc;
	/* Gets the Shell's default allocator */
	if (::SHGetMalloc(&pMalloc) == NOERROR)
	{
		BROWSEINFO bi;
		char pszBuffer[MAX_PATH];
		LPITEMIDLIST pidl;
		// Get help on BROWSEINFO struct - it's got all the bit settings.
		bi.hwndOwner = GetSafeHwnd();
		bi.pidlRoot = NULL;
		bi.pszDisplayName = pszBuffer;
		bi.lpszTitle = _T("Select a Starting Directory");
		bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
		bi.lpfn = NULL;
		bi.lParam = 0;
		// This next call issues the dialog box.
		if ((pidl = ::SHBrowseForFolder(&bi)) != NULL)
		{
			if (::SHGetPathFromIDList(pidl, pszBuffer))
				_editCoverData = pszBuffer;
		}
		// Free the PIDL allocated by SHBrowseForFolder.
		pMalloc->Free(pidl);
	}
	// Release the shell's allocator.
	pMalloc->Release();
	Invalidate();
	UpdateWindow();
}

void CPrefTab::OnBnClickedDefault() {
	setDefault();
	Invalidate();
	UpdateWindow();
}
#define MESSAGE_CACHE "Cache cleared"

void CPrefTab::OnBnClickedClearCache()
{
	char buffer [MAX_PATH];
	memset (buffer, 0, sizeof(buffer));
	VERIFY(::GetModuleFileName(AfxGetInstanceHandle(), buffer, _MAX_PATH));
	CString sPath = (CString)buffer;
	sPath = sPath.Left(sPath.ReverseFind('\\'));
	sPath += "\\";
	sPath += CACHE_LOCATION;
	sPath += "*";
	memset (buffer, 0, sizeof(buffer));
	strcpy(buffer, sPath);

	SHFILEOPSTRUCT shStr;
	shStr.hwnd=this->m_hWnd;
	shStr.wFunc=FO_DELETE;
	shStr.pFrom=LPCTSTR(buffer);
	shStr.pTo=NULL;
	shStr.fFlags=FOF_NOCONFIRMATION;
	int retval = SHFileOperation(&shStr);

	AfxMessageBox(MESSAGE_CACHE, MB_ICONINFORMATION);
}

BOOL CPrefTab::OnInitDialog() {
	CResizablePage::OnInitDialog();

	// Populate the server list
	_server.AddString(SERVER_US);
	_server.AddString(SERVER_UK);
	_server.AddString(SERVER_DE);
	_server.AddString(SERVER_FR);

	return TRUE;  // return TRUE unless you set the focus to a control
}

void CPrefTab::OnBnClickedBrowseP2P() {
	char szFilters[]= "Executable Files (*.exe)|*.bat|All Files (*.*)|*.*||";
	CFileDialog fileDlg (TRUE, "exe", "*.exe", OFN_FILEMUSTEXIST, szFilters);

	if(fileDlg.DoModal() == IDOK ) {
		// Set the working dir
		char buffer [MAX_PATH];
		memset (buffer, 0, sizeof(buffer));
		VERIFY(::GetModuleFileName(AfxGetInstanceHandle(), buffer, _MAX_PATH));
		CString sPath = (CString)buffer;
		sPath = sPath.Left(sPath.ReverseFind('\\'));
		sPath += "\\";
		SetCurrentDirectory(sPath);

		// Get the info
		_editP2PData = fileDlg.GetPathName();
	}
	fileDlg.EndModalState();
}

//#define	URL_XML_ID	"t=moretunes03-20&dev-t=DPIL9EE9TKNOA&f=xml&mode=music&type=heavy&" // real stuff (contains associate id and dev token)
#define	URL_XML_ID	"AWSAccessKeyId=08YNE512HDEKXNQEC7R2&Operation=ItemSearch&SearchIndex=Music&ResponseGroup=Large&" // real stuff (contains associate id and dev token)

CString CPrefTab::getServer(void)
{
	CString xmlServer;
//	if (_serverData == 0)
		xmlServer = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&";
	if (_serverData == 1)
		xmlServer = "http://webservices.amazon.co.uk/onca/xml?Service=AWSECommerceService&";
	else if (_serverData == 2)
		xmlServer = "http://webservices.amazon.de/onca/xml?Service=AWSECommerceService&";
	else if (_serverData == 3)
		xmlServer = "http://webservices.amazon.fr/onca/xml?Service=AWSECommerceService&";
	else if (_serverData == 4)
		xmlServer = "http://webservices.amazon.co.jp/onca/xml?Service=AWSECommerceService&"; 
	xmlServer += URL_XML_ID;
	return xmlServer;
}

int CPrefTab::LaunchOnStartup(int on) {
	HKEY hKey;
	LPCTSTR szValue = "moreTunes";

	if (RegCreateKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &hKey, 0))
		return FALSE;
	if (on == TRUE)
	{
		HKEY hKeyPath;	
		char pathToMoreTunes[1024];
		DWORD cbData = 1024;

		RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\moreTunes", 0, KEY_QUERY_VALUE, &hKeyPath);
		RegQueryValueEx(hKeyPath, "DisplayIcon", 0, 0, (LPBYTE)&pathToMoreTunes, &cbData);
		RegCloseKey(hKeyPath);
		RegSetValueEx(hKey, szValue, 0, REG_SZ, (BYTE*)pathToMoreTunes, (DWORD) strlen(pathToMoreTunes));
	}
	else
		RegDeleteValue(hKey, szValue);
	RegCloseKey(hKey);
	return TRUE;
}

CPrefTab::~CPrefTab()
{
}

void CPrefTab::DoDataExchange(CDataExchange* pDX)
{
	CResizablePage::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT4, _editP2P);
	DDX_Control(pDX, IDC_EDIT5, _editCover);
	DDX_Control(pDX, IDC_EDIT3, _encoder);
	DDX_Control(pDX, IDC_EDIT2, _copyright);
	DDX_Control(pDX, IDC_EDIT1, _fileName);
	DDX_Control(pDX, IDC_COMBO1, _server);
	DDX_Control(pDX, IDC_CHECK1, _autoSearch);
	DDX_Control(pDX, IDC_CHECK2, _autoScan);
	DDX_Control(pDX, IDC_CHECK3, _results);
	DDX_Control(pDX, IDC_CHECK4, _duplicate);
	DDX_Control(pDX, IDC_CHECK5, _onlyV1);
	DDX_Control(pDX, IDC_CHECK6, _existing);
	DDX_Control(pDX, IDC_CHECK9, _systray);
	DDX_Control(pDX, IDC_CHECK8, _trackFormat);
	DDX_Control(pDX, IDC_CHECK10, _onStartup);
	DDX_Control(pDX, IDC_CHECK7, _proxy);
	DDX_Control(pDX, IDC_EDIT7, _proxyServer);
	DDX_Control(pDX, IDC_CHECK11, _numFormat);
	DDX_Control(pDX, IDC_CHECK12, _coverArt);
	DDX_Control(pDX, IDC_CHECK13, _WMPCompatible);
}


BEGIN_MESSAGE_MAP(CPrefTab, CResizablePage)
	ON_BN_CLICKED(IDC_BUTTON2, OnBnClickedDefault)
	ON_BN_CLICKED(IDC_BUTTON1, OnBnClickedSave)
	ON_BN_CLICKED(IDC_BUTTON3, OnBnClickedClearCache)
	ON_BN_CLICKED(IDC_BUTTON5, OnBnClickedBrowseP2P)
	ON_BN_CLICKED(IDC_BUTTON4, OnBnClickedBrowseCover)
	ON_WM_PAINT()
END_MESSAGE_MAP()


